#include "mytimer.h"

#include <QPainter>
#include <QTimer>

#include <QPropertyAnimation>

MyTimer::MyTimer(QWidget *parent)
    : QWidget{parent}
{
    timer.setInterval(1000);  // 1s

    connect(&timer, &QTimer::timeout, this, [&] {
        --current;
        repaint();
        if (current == 0) {
            emit time_up();
            timer.stop();
        }
    });

    anim = new QPropertyAnimation(this, "progress", this);
    anim->setEasingCurve(QEasingCurve::OutQuad);
    connect(anim, &QPropertyAnimation::valueChanged, this, [&] {repaint();});
}

void MyTimer::set_duration(int dur) {
    int old_current = current;
    int old_duration = duration;

    duration = current = dur;

    anim->setDuration(2000*(1-(float)old_current/old_duration));
    anim->setStartValue((float)old_current/old_duration*duration);
    anim->setEndValue(duration);
    anim->start();
}

void MyTimer::paintEvent(QPaintEvent* event) {
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    int radius = std::min(rect().width(), rect().height())/2;
    radius *= .8;

    auto timer_rect = QRect{-radius, -radius, radius*2, radius*2};

    painter.translate(rect().width()/2, rect().height()/2);
    painter.rotate(-90);  // 进度条从顶部开始减少

    //>>>>>>>>>>>>>>>>>>>>>>>>

        // BACKGROUND
        QPen back_pen;
        back_pen.setColor("#AFB0B2");
        back_pen.setWidth(4);
        painter.setPen(back_pen);
        painter.drawEllipse(timer_rect);

        // OUTLINE
        QPen outline_pen;
        outline_pen.setColor(lap%2==0 ? "#428EC0" : "000000");
        outline_pen.setWidth(8);
        outline_pen.setCapStyle(Qt::RoundCap);
        painter.setPen(outline_pen);
        painter.drawArc(timer_rect, 0, 360*16*(current/(float)duration));

        // PROGRESSBAR
        QPen front_pen;
        front_pen.setColor(lap%2==0 ? "#6B8EA5" : "#696A6B");
        front_pen.setWidth(6);
        front_pen.setCapStyle(Qt::RoundCap);
        painter.setPen(front_pen);
        painter.drawArc(timer_rect, 0, 360*16*(current/(float)duration));

    //<<<<<<<<<<<<<<<<<<<<<<<<<

    painter.rotate(90);
    painter.translate(-rect().width()/2, -rect().height()/2);

    // TEXT
    const int offsety = 25;

    auto lap_label_rect = rect();
    lap_label_rect.setHeight(rect().height()/2-offsety);
    painter.setPen("#707D8E");
    painter.setFont(QFont("Arial", 18));
    painter.drawText(lap_label_rect, Qt::AlignHCenter|Qt::AlignBottom, QString("Lap %1").arg(lap));

    auto time_label_rect = rect();
    time_label_rect.setY(rect().height()/2-offsety);
    painter.setPen(lap%2==0 ? "#2980B9" : "000000");
    painter.setFont(QFont("Arial", 54, QFont::Bold));
    painter.drawText(time_label_rect, Qt::AlignHCenter|Qt::AlignTop, formated_current());
}
